#/usr/bin/env python3
# -*- coding: utf-8 -*-
import warnings
import urllib3
import gitlab
from gitlab import Gitlab


# 禁用 InsecureRequestWarning 警告
warnings.filterwarnings("ignore", category=urllib3.exceptions.InsecureRequestWarning)


class GitClient:
    def __init__(self, api_url, access_token):
        self.api_url = api_url
        self.access_token = access_token
        self.gitClient = Gitlab(api_url, private_token=access_token, ssl_verify=False)

    def GetProjectID(self, project_name):
        #print(f"开始查找项目：{project_name}")
        projects = self.gitClient.projects.list(search=project_name)
        #print(projects)
        for proj in projects:
            #print(project)
            if project_name == proj.name:
                return proj.id
        print(f"未找到项目：{project_name}")
        return 0


    def existBranch(self, project_id, branch_name):
        branches = self.gitClient.projects.get(project_id).branches.list(per_page=1024)
        return any(branch.name == branch_name for branch in branches)

    def isSameBranch(self, project_id, branch1, branch2):
        project = self.gitClient.projects.get(project_id)
        commits1 = project.commits.list(ref_name=branch1, per_page=1, get_all=False)
        commits2 = project.commits.list(ref_name=branch2, per_page=1, get_all=False)
        
        # 比较两个分支的最新 commit 是否相同
        if commits1 and commits2 and commits1[0].id == commits2[0].id:
            print(f"两个分支的最新 commit 是相同的。")
            print(f"Commit ID: {commits1[0].id}")
            return True
        else:
            print(f"两个分支的最新 commit 不同。")
            if commits1:
                print(f"{branch1} 的最新 commit ID: {commits1[0].id}")
            if commits2:
                print(f"{branch2} 的最新 commit ID: {commits2[0].id}")
            return False

    # 函数：检查分支是否存在
    def ExistBranch(self, project_name, branch_name):
        id = self.GetProjectID(project_name)
        if id == 0:
            print(f"没找到项目{project_name}") 
        
        print(f"找到项目{project_name} ID：{id}")        
        return self.existBranch(id, branch_name)
        
    def createBranch(self, project_id, source_branch, new_branch):
        self.gitClient.projects.get(project_id).branches.create({'branch': new_branch, 'ref': source_branch})
        print(f"分支 {new_branch} 已创建.")

    # 函数：删除分支
    def DeleteBranch(self, project_id, branch_name):
        self.gitClient.projects.get(project_id).branches.delete(branch_name)
        print(f"分支 {branch_name} 已删除.")

    #函数：创建分支
    def CreateBranch(self, source_branch, new_branch):
        id = self.GetProjectID(project_name)
        if id == 0:
            print(f"没找到项目{project_name}") 
        
        print(f"找到项目{project_name} ID：{id}")    

        if not self.existBranch(id, new_branch):
            self.createBranch(id, source_branch, new_branch)            
        else:
            print(f"分支 {new_branch} 已存在.")


